package com.briup.corejava.chap12;

import com.briup.corejava.chap12.bean.Student;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 登陆的客户端
 * 从键盘录入帐号和密码
 * 包装成student对象，发送给服务器，得到是否登陆成功的响应
 */
public class Test065_LoginClient {
    public static void main(String[] args) {
        Socket socket = null;
        String ip = "localhost";
        int port = 8888;
        Scanner sc = new Scanner(System.in);
        try {
            socket = new Socket(ip,port);
            // 从键盘录入帐号和密码
            System.out.println("正在连接服务器...");
            System.out.println("请输入帐号：");
            String name = sc.nextLine();
            System.out.println("请输入密码：");
            String password = sc.nextLine();
            // 根据输入的信息构建对象
            Student s = new Student();
            s.setName(name);
            s.setPassword(password);
            // 写入到socket中
            ObjectOutput oos = new ObjectOutputStream(
                    socket.getOutputStream());
            oos.writeObject(s);
            oos.flush();

            // 从服务器接收到的数据可能是一句话
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                            socket.getInputStream()));
            String result = br.readLine();
            // 输出一下
            System.out.println("服务器返回的消息："+result);

            oos.close();
            br.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
